﻿#define LOGWRITE
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace myCommon.Utils
{
    public  partial class DateTimeFunc
    {
        public static  void WaitMS(int MSeconds)
        {
            long nowMS;
            long starttime = DateTime.Now.Ticks / 10000;
            long endtime = starttime + MSeconds;
            do
            {
                nowMS = DateTime.Now.Ticks / 10000;
            } while (nowMS < endtime);
        }
        /// <summary>结果为：1999-11-11 12:22:22
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static  string ConvertDateTime(DateTime datetime)
        {
            //1999-11-11 12:22:22
            
            return ConvertDateTime(datetime,false);
        }
        /// <summary>如果ToLongInt==True，结果为：19830525103000；如果ToLongInt==False，结果为：1983-05-25 10:30:00
        /// </summary>
        /// <param name="datetime"></param>
        /// <param name="ToLongInt"></param>
        /// <returns></returns>
        public static string  ConvertDateTime(DateTime datetime, bool ToLongInt)
        {
            //1999-11-11 12:22:22
            string year, month, day;
            string time;
            string YYYY="0000",MM="00",DD="00";
            string hh="00",mm="00",ss="00";
            int enddot = 0;

            if (ToLongInt)
            {
                YYYY = datetime.Year.ToString("0000");
                MM = datetime.Month.ToString("00");
                DD = datetime.Day.ToString("00");

                hh = datetime.Hour.ToString("00");
                mm = datetime.Minute.ToString("00");
                ss = datetime.Second.ToString("00");

                time = YYYY + MM + DD + hh + mm + ss;
            }
            else
            {
                year = datetime.Year.ToString();
                month = datetime.Month.ToString();
                day = datetime.Day.ToString();
                time = datetime.TimeOfDay.ToString();
                enddot = time.IndexOf('.');
                if (enddot > 0) time = time.Substring(0, time.Length - enddot);
                time = year + "-" + month + "-" + day + " " + time;
            }
            return time;
        }

    }

    public static partial class Info
    {
        /// <summary> Get current directory name,结尾带“\”.if failed, return "ERROR"
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentDirctory()
        {
            string dirname;
            int LastFlag;
            string filename;
            try
            {
                filename = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
                //Console.WriteLine(filename);
                LastFlag = filename.LastIndexOf('\\');
                dirname = filename.Substring(0, LastFlag)+"\\";
                return dirname;
            }
            catch 
            {
                return "ERROR";
            }
        }

        /// <summary>return the application filename with full path,if WithEXE=true, return filename with ".exe"
        /// </summary>
        public static string GetAppFullName(bool WithEXE)
        {
            string FullName= System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            if (WithEXE) return FullName;
            else return FullName.Substring(FullName.LastIndexOf('.'));
        }

        /// <summary>Only return the application's file name, if WithEXE=true, return filename with ".exe", else only return filename
        /// </summary>
        public static string GetOnlyAppName(bool WithEXE)
        {
            string FullName = GetAppFullName(true);
            FullName = FullName.Substring(FullName.LastIndexOf('\\') + 1);
            if (WithEXE) return FullName;
            else return FullName.Substring(0, FullName.LastIndexOf('.'));
        }

        /// <summary>Only return the application's file name, if WithEXE=true, return filename with ".exe", else only return filename
        /// </summary>
        public static string[] SplitPathAndFileName(string fileName)
        {
            string[] pathResult=new string[2];
            pathResult[0] = fileName.Substring(0, fileName.LastIndexOf('\\'));
            pathResult[1]= fileName.Substring(fileName.LastIndexOf('\\') + 1);
            return pathResult;

        }
    }

    /// <summary>日志相关功能
    /// </summary>
    public static partial class LogFunc
    {
        /// <summary>如果LogPath中包含":"，说明是绝对路径；否则直接写在当前路径下的LogPath文件里。
        /// </summary>
        /// <param name="Log">日志内容</param>
        /// <param name="LogPath">日志路径，可以是绝对路径，也可以是一个文件名</param>
        public static void LogWrite(string Log, string LogPath)
        {
#if LOGWRITE
            string FullPath = "";
            //it's reference path, not absolute path
            if (LogPath.IndexOf(':') > 0) { FullPath = LogPath; }
            else { FullPath = General.Info.GetCurrentDirctory() + LogPath; }
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(FullPath, true))
            {
                sw.WriteLine(DateTime.Now.ToString() + ":" + Log);
                //sw.Close();
            }
#endif
        }

        public static void LogWrite(string Log)
        {
#if LOGWRITE
            string LogFilePath;
            LogFilePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            LogFilePath = LogFilePath.Substring(0, LogFilePath.LastIndexOf('.'));
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(LogFilePath, true))
            {
                //sw.Write(DateTime.Now.ToString() + ":" + Log+ "\r\n");
                sw.WriteLine(DateTime.Now.ToString() + ": " + Log);
                //sw.Close();
            }
#endif
        }
        public static void LogWriteInDay(string Log)
        {
#if LOGWRITE
            string LogFilePath;
            LogFilePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            LogFilePath = LogFilePath.Substring(0, LogFilePath.LastIndexOf('.'));
            LogFilePath += "_" + DateTime.Now.Year.ToString("0000") + DateTime.Now.Month.ToString("00") + DateTime.Now.Day.ToString("00") + ".log";
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(LogFilePath, true))
            {
                sw.WriteLine(DateTime.Now.ToString() + ":" + Log);
                //sw.Close();
            }
#endif
        }
    }

    /// <summary>声音相关功能
    /// </summary>
    public static partial class SoundFunc
    {
        public static void playsound(string SoundPath)
        {
            System.Media.SoundPlayer sndPlayer = new System.Media.SoundPlayer(SoundPath);
            sndPlayer.Play();
            sndPlayer.Dispose();
        }
    }

    /// <summary>一些转换功能
    /// </summary>
    public static partial class Converter
    {
        /// <summary>返回处理后的十六进制字符串 
        /// </summary>
        public static string StrToHex(string mStr) 
        {
            return BitConverter.ToString(
            ASCIIEncoding.Default.GetBytes(mStr)).Replace("-", " ");
        }
    }


    /// <summary>图像功能
    /// </summary>
    public static partial class ImageClass
    {
        /// <summary>返回处理后的十六进制字符串 
        /// </summary>
        public static System.Drawing.Image GetImgFromBMP(string filename)
        {
            //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(filename);
            //System.Drawing.Image img;
            return null;
        }

        public static Bitmap DrawLineInPicture(System.Drawing.Bitmap bmp, Point p0, Point p1, Color LineColor, int LineWidth, DashStyle ds)
        {
            if (bmp == null) return null;
            if (p0.X == p1.X || p0.Y == p1.Y) return bmp;
            Graphics g = Graphics.FromImage(bmp);
            Brush brush = new SolidBrush(LineColor);
            Pen pen = new Pen(brush, LineWidth);
            //pen.Alignment = PenAlignment.Inset; 
            pen.DashStyle = ds;
            g.DrawLine(pen, p0, p1);
            g.Dispose();
            return bmp;
        }

        public static Bitmap resizePic(string fn)
        {
            Bitmap bmp = new Bitmap(fn);
            /*
            Graphics g=Graphics;
            //g.FillRectangle(Brushes.White, ClientRectangle);
            int width = bmp.Width;
            int height = bmp.Height;
            // 改变图像大小使用低质量的模式
            g.InterpolationMode = InterpolationMode.NearestNeighbor;
            g.DrawImage(bmp, new Rectangle(10, 10, 120, 120), // source rectangle

            new Rectangle(0, 0, width, height), // destination rectangle
            GraphicsUnit.Pixel);
            // 使用高质量模式
            //g.CompositingQuality = CompositingQuality.HighSpeed;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(
            bmp,
            new Rectangle(130, 10, 120, 120),
            new Rectangle(0, 0, width, height),
            GraphicsUnit.Pixel);
            */
            return bmp;
        }

        public static Bitmap BytesToBitmap(byte[] Bytes)
        {
            MemoryStream stream = null;
            try
            {
                stream = new MemoryStream(Bytes);
                return new Bitmap((Image)new Bitmap(stream));
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
            finally
            {
                stream.Close();
            }
        }

        //Image to byte[]   
        public static byte[] BitmapToBytes(Bitmap Bitmap)
        {
            MemoryStream ms = null;
            try
            {
                ms = new MemoryStream();
                Bitmap.Save(ms, Bitmap.RawFormat);
                byte[] byteImage = new Byte[ms.Length];
                byteImage = ms.ToArray();
                return byteImage;
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            finally
            {
                ms.Close();
            }
        }
        /*
        public static Image BitmapToImage(Bitmap bitmap)
        {
            var bytes = BitmapToBytes(bitmap);
            Stream stream = new Stream(bytes);
            return Image.FromStream(stream);
        }
        public static Stream BytesToStream(byte[] bytes)
        {
            Stream stream = new Stream(bytes);
            return stream;
        }
        */

    }




    public static partial class Test
    {
        public static bool IsNumber(string str)
        {
            int a = 0;
            return int.TryParse(str, out a);
        }
    }

    public static partial class Stream
    {
        public static string ReadFromFile(string filepath)
        {
            string sTemp;
            System.IO.StreamReader sr = new System.IO.StreamReader(filepath);
            sTemp = sr.ReadToEnd();
            sr.Close();
            return sTemp;
        }
    }

    public static partial class encrypt
    {
        private const int HZStart = 0x4E00;
        private const int HZEnd = 0x9FA5;
        private const int ASCII_Readable_Start = 0x20;
        private const int ASCII_Readable_End = 0x7E;

        public static string encryptString(string str1,int offset)
        {
            char[] buf=new char[1024];
            int strLen = str1.Length;
            int iBeforConvert = 0;
            int iAfterConvert = 0;
            int i;
            int iSign = 1;//符号正负
            int pos = 0;
            int iRealOffset = 0;
            buf=str1.ToCharArray();
            iSign = Math.Abs(offset)/offset;
            for (i = 0; i < strLen; i++)
            {
                iBeforConvert =(int)buf[i];
                if (iBeforConvert >= HZStart && iBeforConvert <=HZEnd)//汉字
                {
                    pos=(i % (HZEnd -HZStart));
                    iRealOffset = iSign * (pos + Math.Abs(offset));
                    if (iBeforConvert + iRealOffset > HZEnd)
                    {
                        iAfterConvert = iBeforConvert + iRealOffset - HZEnd + HZStart - 1;
                    }
                    else if (iBeforConvert + iRealOffset < HZStart)
                    {
                        iAfterConvert = iBeforConvert + iRealOffset + HZEnd - HZStart + 1;
                    }
                    else
                    {
                        iAfterConvert = iBeforConvert + iRealOffset;
                    }
                }


                if (iBeforConvert >= ASCII_Readable_Start && iBeforConvert <= ASCII_Readable_End)//字母
                {
                    pos=i%(ASCII_Readable_End-ASCII_Readable_Start);
                    iRealOffset = iSign * (pos + Math.Abs(offset));
                    if (iBeforConvert + iRealOffset > ASCII_Readable_End)
                    {
                        iAfterConvert = iBeforConvert + iRealOffset - ASCII_Readable_End + ASCII_Readable_Start - 1;
                    }
                    else if (iBeforConvert + iRealOffset < ASCII_Readable_Start)
                    {
                        iAfterConvert = iBeforConvert + iRealOffset + ASCII_Readable_End - ASCII_Readable_Start + 1;
                    }
                    else
                    {
                        iAfterConvert = iBeforConvert + iRealOffset;
                    }
                }
                buf[i] = (char)iAfterConvert;
                
            }
            StringBuilder sb = new StringBuilder();
            sb.Append(buf);
            return sb.ToString ();
        }
    
    }
}